package com.hwl.lab.controller;

import com.hwl.lab.entity.Role;
import com.hwl.lab.entity.RoleAndMenu;
import com.hwl.lab.entity.User;
import com.hwl.lab.repository.RoleAndMenuRepository;
import com.hwl.lab.service.RoleService;
import com.hwl.lab.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@CrossOrigin //允许跨域请求
@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleAndMenuRepository roleAndMenuRepository;

    //查询所有（分页）
    @GetMapping("/findRoleAll/{page}/{size}")
    public Page<Role> findRoleAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        return roleService.findAll(page,size);
    }
    //查询所有不分页
    @GetMapping("/findRoleAll")
    public List<Role> findAll(){
        return roleService.findAll();
    }
    //账号查询
    @GetMapping("/findByRoleid/{roleid}")
    public Role findByRoleid(@PathVariable("roleid") String roleid){
        return roleService.findByRoleid(roleid);
    }

    @GetMapping("/findByRoleidF/{roleid}")
    public List<Role> findByUserid(@PathVariable("roleid") String roleid){
        if (roleService.findByRoleid(roleid) != null) {
            List<Role> roles = new ArrayList<>();
            roles.add(roleService.findByRoleid(roleid));
            return roles;
        } else {
            return null;
        }
    }
    //添加，修改
    @PostMapping("/saveRole")
    public void saveRole(@RequestBody(required=false) Role role){
        roleService.saveRole(role);
    }

    //通过账号删除
    @PostMapping("/deleteRole/{id}")
    public void deleteRole(@PathVariable("id") Long id){
        roleService.deleteById(id);
    }
    //添加对应菜单
    @PostMapping("/saveRoleAndMenu/{roleid}/{menuname}")
    public void saveUserAndRole(@PathVariable("roleid") String roleid, @PathVariable("menuname") String menuname) {
        RoleAndMenu roleAndmenu = new RoleAndMenu();
        roleAndmenu.setRoleid(roleid);
        roleAndmenu.setMenuname(menuname);
        roleAndMenuRepository.save(roleAndmenu);
    }

    // 获取对应菜单
    @PostMapping("/findByUseridM/{roleid}")
    public String[] findByUseridU(@PathVariable("roleid") String roleid) {
        List<RoleAndMenu> roleAndMenus = new ArrayList<>();
        roleAndMenus = roleAndMenuRepository.findMneunameByRoleid(roleid);
        String[] num = new String[100];
        for (int n = 0;n<roleAndMenus.size();n++) {
            num[n] = roleAndMenus.get(n).getMenuname();
        }
        return   num;
    }
    // 级联删除对应菜单
    @PostMapping("/deleteRoleM/{roleid}")
    public void deleteByIdU(@PathVariable("roleid") String roleid){
        roleAndMenuRepository.deleteByRoleid(roleid);
    }

}
